<?php
/**
 * [ Random Framework ]
 *
 * @version 2.0.0 (build 20130520)
 *
 * @link http://0x00.sinaapp.com/random.html
 * 
 * @author Coseylee (Coseylee@gmail.com).
 *
 */

class pathinfo_route extends random_route
{
	function url_parse()
	{
		$on = (bool)$this -> config['pathinfo'];
		
		// 兼容模式组装 PATHINFO
		if ($on == true)
		{
			$_GET = array(); // 清空$_GET
			if (isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING']))
			{
				$query_string = parse_url($_SERVER['QUERY_STRING']);
				$_SERVER['PATH_INFO'] = '/'.$query_string['path'];
				if (isset($query_string['query']))
				{
					parse_str($query_string['query'], $_GET);
				}
			}
			if (isset($_GET[$_SERVER['QUERY_STRING']])) unset($_GET[$_SERVER['QUERY_STRING']]);
		}
		
		// 在非POST方法时对不符合标准的URL重新组装，再跳转
		if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST' && !empty($_GET) && count($_GET) > 0)
		{
			$pre = $on == true ? '?' : '/';
			$forward = $GLOBALS['RANDOM']['route']['url_base'].$pre.substr($_SERVER['PATH_INFO'], 1).'/';
			foreach ($_GET as $k => $v)
			{
				if (!empty($v)) $forward .= $k.'/'.$v;
			}
			header('HTTP/1.1 301 Moved Permanently');
			header('Location: '.$forward);
			exit;
		}
		
		// 分析URL参数，组装 $_GET
		if (isset($_SERVER['PATH_INFO']) && !empty($_SERVER['PATH_INFO']))
		{
			$path_info = explode('/', $_SERVER['PATH_INFO']);
			array_shift($path_info);

			$controller_dir = '';
			$controller_dir_level = 0;

			foreach ($path_info as $k => $v)
			{
				if (is_dir($GLOBALS['RANDOM']['controller_path'].$controller_dir.$v))
				{
					if ($controller_dir.$v != '')
					{
						$controller_dir = $controller_dir.$v.DIR_SEP;
					}
					$controller_dir_level++;
					continue;
				}

				switch ($k - $controller_dir_level)
				{
					case 0:
					$_GET[$this -> config['controller_name']] = $v;
					break;
					case 1:
					$_GET[$this -> config['action_name']] = $v;
					break;
					default:
					{
						if ($k%2 == 0 && !empty($path_info[$k]))
						{
							$_GET[$path_info[$k]] = isset($path_info[$k+1]) ? $path_info[$k+1] : '';
						}
					}
				}
			}
			$GLOBALS['RANDOM']['route']['controller_sub_dir'] = $controller_dir;
		}
	}
	
	function url_create($controller = '', $action = '', $args = array(), $query_string = '')
	{
		$config = $GLOBALS['RANDOM']['route'];
		$url = $config['url_base'].(CONTORLLER_SUB_DIR ? '/'.CONTORLLER_SUB_DIR : '');
		
		if ($controller === '' && $action === '' && empty($args))
		{
			return $url;
		}
		
		$pre = !$config['pathinfo'] ? '/' : '?';
		
		$url .= $pre.($controller !== '' ? $controller : $config['controller']);
		
		if ($action !== '' || !empty($args))
		{
			$action = $action === '' ? $config['action'] : $action;
			$url .= '/'.$action;
		}
		
		foreach ($args as $k => $v)
		{
			$url .= '/'.$k.'/'.$v;
		}
		
		if ($query_string !== '')
		{
			$url .= '?'.$query_string;
		}
		return $url;
	}
}